<template>
  <div class="code-generator">
    <div class="generator-header">
      <div class="title-wrapper">
        <h2><i class="fas fa-code"></i> 代码生成器</h2>
        <div class="subtitle">快速集成API到您的项目中</div>
      </div>
      <div class="tips">
        <i class="fas fa-lightbulb"></i>
        <span>提示：生成的代码仅供参考，请根据实际业务需求进行调整</span>
      </div>
    </div>

    <div class="language-selector">
      <div 
        v-for="lang in languages" 
        :key="lang.id"
        :class="['lang-option', { active: selectedLang === lang.id }]"
        @click="selectedLang = lang.id"
      >
        <i :class="lang.icon"></i>
        <span>{{ lang.name }}</span>
      </div>
    </div>

    <div class="code-showcase">
      <div class="code-header">
        <div class="file-info">
          <span class="file-icon"><i :class="currentLang.icon"></i></span>
          <span class="file-name">{{ currentLang.fileName }}</span>
        </div>
        <div class="code-actions">
          <button 
            class="action-btn"
            @click="copyCode"
            :class="{ 'copied': isCopied }"
          >
            <i class="fas" :class="isCopied ? 'fa-check' : 'fa-copy'"></i>
            {{ isCopied ? '已复制' : '复制代码' }}
          </button>
        </div>
      </div>
      
      <div class="code-content" ref="codeContainer">
        <div class="line-numbers">
          <span v-for="n in lineCount" :key="n">{{ n }}</span>
        </div>
        <pre><code v-html="highlightedCode"></code></pre>
      </div>

      <div class="code-notes">
        <div class="note-header">
          <i class="fas fa-info-circle"></i>
          <span>代码说明</span>
        </div>
        <ul class="note-list">
          <li v-for="(note, index) in currentLang.notes" :key="index">
            {{ note }}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'

export default {
  name: 'GenerateCode',
  
  props: {
    apiUrl: {
      type: String,
      required: true
    },
    method: {
      type: String,
      default: 'GET'
    },
    params: {
      type: Object,
      default: () => ({})
    }
  },

  data() {
    return {
      selectedLang: 'java',
      isCopied: false,
      languages: [
        {
          id: 'java',
          name: 'Java',
          icon: 'fab fa-java',
          fileName: 'ApiClient.java',
          highlight: 'java',
          notes: [
            '使用 Java 11+ HttpClient 发送请求',
            '支持异步调用',
            '需要处理异常情况'
          ]
        },
        {
          id: 'python',
          name: 'Python',
          icon: 'fab fa-python',
          fileName: 'api_client.py',
          highlight: 'python',
          notes: [
            '使用 requests 库发送请求',
            '简单直观的 API 调用方式',
            '建议添加错误处理'
          ]
        },
        {
          id: 'nodejs',
          name: 'Node.js',
          icon: 'fab fa-node-js',
          fileName: 'apiClient.js',
          highlight: 'javascript',
          notes: [
            '使用 axios 发送请求',
            '支持 Promise 和 async/await',
            '包含错误处理示例'
          ]
        },
        {
          id: 'php',
          name: 'PHP',
          icon: 'fab fa-php',
          fileName: 'api_client.php',
          highlight: 'php',
          notes: [
            '使用 cURL 发送请求',
            '包含基本的错误处理',
            '可以集成到现有项目中'
          ]
        }
      ]
    }
  },

  computed: {
    currentLang() {
      return this.languages.find(lang => lang.id === this.selectedLang)
    },

    lineCount() {
      return this.generatedCode.split('\n').length
    },

    highlightedCode() {
      const code = this.generatedCode
      if (this.currentLang) {
        return hljs.highlight(code, { 
          language: this.currentLang.highlight 
        }).value
      }
      return code
    },

    generatedCode() {
      const params = Object.entries(this.params)
        .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
        .join('&')
      
      const fullUrl = params ? `${this.apiUrl}?${params}` : this.apiUrl

      const templates = {
        java: 
`import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class ApiClient {
    private static final HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

    public static void main(String[] args) {
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("${fullUrl}"))
                    .header("Content-Type", "application/json")
                    .method("${this.method}", HttpRequest.BodyPublishers.noBody())
                    .build();

            HttpResponse<String> response = client.send(request, 
                    HttpResponse.BodyHandlers.ofString());
            
            System.out.println("Status: " + response.statusCode());
            System.out.println("Response: " + response.body());
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}`,
        python: 
`import requests

def call_api():
    try:
        headers = {
            'Content-Type': 'application/json'
        }
        
        response = requests.${this.method.toLowerCase()}(
            '${fullUrl}',
            headers=headers,
            timeout=10
        )
        
        response.raise_for_status()  # 检查响应状态
        return response.json()
        
    except requests.exceptions.RequestException as e:
        print(f"Error calling API: {e}")
        return None

if __name__ == '__main__':
    result = call_api()
    print(result)`,
        nodejs: 
`const axios = require('axios');

async function callApi() {
    try {
        const response = await axios({
            method: '${this.method.toLowerCase()}',
            url: '${fullUrl}',
            headers: {
                'Content-Type': 'application/json'
            },
            timeout: 10000
        });

        console.log('Status:', response.status);
        console.log('Data:', response.data);
        return response.data;
        
    } catch (error) {
        console.error('Error calling API:', error.message);
        throw error;
    }
}

// 使用示例
callApi()
    .then(data => console.log('Success:', data))
    .catch(error => console.error('Failed:', error));`,
        php: 
`<?php

function callApi() {
    $curl = curl_init();
    
    curl_setopt_array($curl, [
        CURLOPT_URL => '${fullUrl}',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => '${this.method}',
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json'
        ],
    ]);

    $response = curl_exec($curl);
    $error = curl_error($curl);
    
    curl_close($curl);
    
    if ($error) {
        throw new Exception("Error calling API: " . $error);
    }
    
    return json_decode($response, true);
}

try {
    $result = callApi();
    print_r($result);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}`
      }

      return templates[this.selectedLang] || ''
    }
  },

  methods: {
    async copyCode() {
      try {
        await navigator.clipboard.writeText(this.generatedCode)
        this.isCopied = true
        setTimeout(() => {
          this.isCopied = false
        }, 2000)
      } catch (err) {
        console.error('复制失败:', err)
      }
    }
  }
}
</script>

<style scoped>
.code-generator {
  background: white;
  border-radius: 1rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.generator-header {
  padding: 1.5rem;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
}

.title-wrapper {
  margin-bottom: 1rem;
}

.title-wrapper h2 {
  font-size: 1.5rem;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.subtitle {
  margin-top: 0.5rem;
  font-size: 0.875rem;
  opacity: 0.9;
}

.tips {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 0.5rem;
  font-size: 0.875rem;
}

.tips i {
  color: #fbbf24;
}

.language-selector {
  display: flex;
  gap: 0.5rem;
  padding: 1rem;
  border-bottom: 1px solid #e5e7eb;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.language-selector::-webkit-scrollbar {
  display: none;
}

.lang-option {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.25rem;
  background: transparent;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
  color: #6b7280;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
}

.lang-option:hover {
  border-color: #6366f1;
  color: #6366f1;
}

.lang-option.active {
  background: #6366f1;
  border-color: #6366f1;
  color: white;
}

.lang-option i {
  font-size: 1.25rem;
}

.code-showcase {
  padding: 1.5rem;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.file-name {
  font-family: 'Fira Code', monospace;
  color: #6b7280;
  font-size: 0.875rem;
}

.action-btn {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: #f3f4f6;
  border: none;
  border-radius: 0.375rem;
  color: #374151;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn:hover {
  background: #e5e7eb;
}

.action-btn.copied {
  background: #34d399;
  color: white;
}

.code-content {
  position: relative;
  background: #282c34;
  border-radius: 0.5rem;
  overflow: hidden;
  display: flex;
}

.line-numbers {
  padding: 1.5rem 0.75rem;
  background: rgba(255, 255, 255, 0.05);
  color: #636e7b;
  font-family: 'Fira Code', monospace;
  font-size: 0.875rem;
  line-height: 1.7;
  text-align: right;
  user-select: none;
}

.line-numbers span {
  display: block;
  min-width: 1.5rem;
}

.code-content pre {
  margin: 0;
  padding: 1.5rem;
  overflow-x: auto;
  flex: 1;
}

.code-content code {
  font-family: 'Fira Code', monospace;
  font-size: 0.875rem;
  line-height: 1.7;
  color: #abb2bf;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.file-icon {
  color: #6366f1;
  font-size: 1.25rem;
}

.code-notes {
  margin-top: 1.5rem;
  padding: 1rem;
  background: #f8fafc;
  border-radius: 0.5rem;
}

.note-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #6366f1;
  font-weight: 500;
  margin-bottom: 0.75rem;
}

.note-list {
  margin: 0;
  padding-left: 1.5rem;
  color: #64748b;
  font-size: 0.875rem;
}

.note-list li {
  margin-bottom: 0.5rem;
}

.note-list li:last-child {
  margin-bottom: 0;
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .code-generator {
    background: #1e293b;
  }

  .code-content {
    background: #282c34;
  }

  .line-numbers {
    background: rgba(0, 0, 0, 0.2);
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .generator-header {
    padding: 1rem;
  }

  .language-selector {
    padding: 0.75rem;
  }

  .lang-option {
    padding: 0.5rem 0.75rem;
  }

  .code-showcase {
    padding: 1rem;
  }

  .code-content pre {
    padding: 1rem;
  }

  .code-content code {
    font-size: 0.8125rem;
  }
}

/* 代码高亮自定义样式 */
:deep(.hljs) {
  background: transparent;
  padding: 0;
}

:deep(.hljs-keyword) {
  color: #c678dd;
}

:deep(.hljs-string) {
  color: #98c379;
}

:deep(.hljs-comment) {
  color: #5c6370;
  font-style: italic;
}

:deep(.hljs-function) {
  color: #61afef;
}

:deep(.hljs-number) {
  color: #d19a66;
}

:deep(.hljs-class) {
  color: #e5c07b;
}

:deep(.hljs-title) {
  color: #61afef;
}

:deep(.hljs-params) {
  color: #abb2bf;
}
</style>
